﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Quartz;
using Quartz.Impl;
using OPCService.Job;
using OPCService.Utils;
using System.Collections.Specialized;

/**
 * 调度器管理类
 */
namespace OPCService.Schedulers
{
    class SchedulerManager
    {
        private readonly IScheduler _scheduler;

        public SchedulerManager()
        {
            var properties = new NameValueCollection
            {
                // 核心配置项
                ["quartz.threadPool.threadCount"] = Math.Max(Environment.ProcessorCount * 2, 20).ToString(),
                ["quartz.threadPool.threadPriority"] = "Normal",

                // 基于内存（最高性能）
                ["quartz.jobStore.type"] = "Quartz.Simpl.RAMJobStore, Quartz",
            };

            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
            _scheduler = schedulerFactory.GetScheduler().Result;
        }

        public async Task StartAsync()
        {
            await _scheduler.Start();
        }

        public async Task ShutdownAsync()
        {
            await _scheduler.Shutdown();
        }

        public async Task ScheduleJobsAsync()
        {
            // 注册 Job（只执行一次）
            var jobTag = JobBuilder.Create<ReadTagFromExcel>()
                .WithIdentity("jobGetTag", "group1")
                .Build();
            var triggerTag = TriggerBuilder.Create()
                .WithIdentity("triggerGetTag", "group1")
                .StartNow()
                .WithSimpleSchedule(x => x
                    .WithRepeatCount(0)
                    .WithMisfireHandlingInstructionNextWithRemainingCount()
                 )
                .Build();
            await _scheduler.ScheduleJob(jobTag, triggerTag);


            // 注册 Job opc800（每 1 秒执行一次）
            var job800 = JobBuilder.Create<Opc800DataCollection>()
                .WithIdentity("jobOpc800", "group2")
                .Build();
            var trigger800 = TriggerBuilder.Create()
                .WithIdentity("triggerOpc800", "group2")
                .StartAt(DateBuilder.FutureDate(5, IntervalUnit.Second)) // 5秒后执行
                .WithSimpleSchedule(x => x
                    .WithIntervalInSeconds(1)
                    .RepeatForever())
                .Build();
            await _scheduler.ScheduleJob(job800, trigger800);

            // 注册 Job opc500（每 1 秒执行一次）
            var job500 = JobBuilder.Create<Opc500DataCollection>()
                .WithIdentity("jobOpc500", "group3")
                .Build();
            var trigger500 = TriggerBuilder.Create()
                .WithIdentity("triggerOpc500", "group3")
                .StartAt(DateBuilder.FutureDate(10, IntervalUnit.Second)) // 10秒后执行
                .WithSimpleSchedule(x => x
                    .WithIntervalInSeconds(1)
                    .RepeatForever())
                .Build();
            await _scheduler.ScheduleJob(job500, trigger500);


            // 注册 Job（每 1 分执行一次）
            var jobRemove = JobBuilder.Create<RemoveHistoryData>()
                .WithIdentity("jobRemove", "group4")
                .Build();
            var triggerRemove = TriggerBuilder.Create()
                .WithIdentity("triggerRemove", "group4")
                .StartAt(DateBuilder.FutureDate(15, IntervalUnit.Second)) // 15秒后执行
                .WithSimpleSchedule(x => x
                    //.WithIntervalInMinutes(1
                    .WithIntervalInSeconds(2)
                    .RepeatForever())
                .Build();
            await _scheduler.ScheduleJob(jobRemove, triggerRemove);


            // 注册 Job2（cron 执行）
            /*var job2 = JobBuilder.Create<Opc500DataCollection>()
                .WithIdentity("jobOpc500", "group5")
                .Build();
            var trigger2 = TriggerBuilder.Create()
                .WithIdentity("triggerOpc500", "group5")
                .WithCronSchedule(ConfigHelper.ReadConfig("cron"))
                .Build();
            await _scheduler.ScheduleJob(job2, trigger2);*/

        }
    }
}
